<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <Header-com @addTodo="addTodo"></Header-com>
        <List-com :todo="todos"></List-com>
        <Footer-com
          :todo="todos"
          @checkAllTodo="checkAllTodo"
          @clearAllTodo="clearAllTodo"
        ></Footer-com>
      </div>
    </div>
  </div>
</template>

<script>
// 引入School组件
import MyHeader from "./components/MyHeader";
import MyList from "./components/MyList";
import MyFooter from "./components/MyFooter";

export default {
  name: "App",
  components: {
    "Header-com": MyHeader,
    "List-com": MyList,
    "Footer-com": MyFooter,
  },
  data() {
    return {
      todos: JSON.parse(localStorage.getItem("todos")) || [
        { id: "001", title: "抽烟", done: false },
        { id: "002", title: "喝酒", done: false },
        { id: "003", title: "开车", done: false },
      ],
    };
  },
  methods: {
    // 添加
    addTodo(obj) {
      this.todos.unshift(obj);
    },
    // 勾选
    checkedTodo(id) {
      this.todos.forEach((item) => {
        if (item.id === id) item.done = !item.done;
      });
    },
    // 删除
    delTodo(id) {
      this.todos = this.todos.filter((item) => item.id !== id);
    },
    // 全选
    checkAllTodo(done) {
      this.todos.forEach((item) => (item.done = done));
    },
    // 清除已完成
    clearAllTodo() {
      this.todos = this.todos.filter((item) => !item.done);
    },
  },
  watch: {
    todos: {
      immediate: true,
      deep: true,
      handler(newVal) {
        localStorage.setItem("todos", JSON.stringify(newVal));
      },
    },
  },
  mounted() {
    this.$bus.$on("checkedTodo", this.checkedTodo);
    this.$bus.$on("delTodo", this.delTodo);
  },
  beforeDestroy() {
    this.$bus.$off(["checkedTodo", "delTodo"]);
  },
};
</script>

<style>
/*base*/
body {
  background: #fff;
}
.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}
.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}
.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}
.btn:focus {
  outline: none;
}
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
